package org.dualr.litelog.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dualr.litelog.dao.CommentDao;
import org.dualr.litelog.dao.PostDao;
import org.dualr.litelog.entity.Comment;
import org.dualr.litelog.utils.LiteLogUtil;

import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class CommentServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(CommentServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		Long postId = Long.parseLong(req.getParameter("postId"));
		if (req.getMethod().equals("POST")) {
			String path = "post?method=view&id=" + postId;
			/* check code */
			int code = Integer.parseInt(req.getParameter("code"));
			HttpSession session = req.getSession();
			int num1 = Integer
					.parseInt(session.getAttribute("num1").toString());
			int num2 = Integer
					.parseInt(session.getAttribute("num2").toString());
			if (code != (num1 + num2)) {
				req.setAttribute("error", "chek code error!");
				try {
					req.getRequestDispatcher(path).forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
				return;
			}
			Text content = new Text(req.getParameter("content"));
			String author = req.getParameter("author");
			Date commentDate = new Date();
			String mail = req.getParameter("mail");
			String website = req.getParameter("website");
			String replyMailMark = req.getParameter("replyMailMark");
			String ip = req.getRemoteAddr();
			Comment comment = new Comment(postId, author, commentDate, content,
					mail, website, ip, replyMailMark);
			PostDao.getInstance().updateHitsorCommentCount(postId,
					"commentCount", "increment");
			String commentId = CommentDao.getInstance().insert(comment);
			req.setAttribute("CommentId", commentId);
			// mail reply
			UserService userService = UserServiceFactory.getUserService();
			if (req.getUserPrincipal() != null) {
				if (userService.isUserAdmin() == true) {
					String mailReply = LiteLogUtil.getInstance().getPropsValue(
							"/litelog.properties", "litelog.mailReply");
					if (mailReply.equals("on")) {
						Long replyId = Long.parseLong(req
								.getParameter("replyId"));
						if (replyId != 0) {
							Comment ct = CommentDao.getInstance().getById(
									replyId);
							if (ct.getReplyMailMark().equals("yes")) {
								String ctMail = ct.getMail();
								String ctGuest = ct.getAuthor();
								String title = LiteLogUtil.getInstance()
										.getPropsValue("/litelog.properties",
												"litelog.mailReplyTitle");
								String mailContent = content.getValue();
								String subject = "Hi~"
										+ ctGuest.getBytes("UTF-8")
										+ ", "
										+ title
										+ "You can view comments and post on "
										+ LiteLogUtil.getInstance()
												.getPropsValue(
														"/litelog.properties",
														"litelog.url")
										+ "?post?method=view&id" + postId;
								sendMail(ctGuest, ctMail, subject, mailContent);
								log.info("mail send");
							}
						}
					}
				}
			}
			resp.sendRedirect(path);
		}
	}

	protected void sendMail(String guest, String mail, String subject,
			String content) {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(LiteLogUtil.getInstance()
					.getPropsValue("/litelog.properties", "litelog.mail")));
			String htmlBody = "<p>--------------------------------NOTICE------------------------------------------"
					+ "<br/>You are receiving this email because you have left messages on the Blog";
			Multipart mp = new MimeMultipart();
			MimeBodyPart htmlPart = new MimeBodyPart();
			htmlPart.setContent(htmlBody, "text/html");
			mp.addBodyPart(htmlPart);
			msg.setContent(mp);
			try {
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
						mail, guest));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			msg.setSubject(subject);
			msg.setText(content);
			Transport.send(msg);
		} catch (AddressException e) {
			// ...
		} catch (MessagingException e) {
			// ...
		}
	}
}
